
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" class="user-search">
      <el-form-item label="搜索：">
        <el-input size="small" v-model="pagination.name" placeholder="输入部门名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column sortable prop="deptId" label="部门id" align="center" width="120">
      </el-table-column>
      <el-table-column sortable prop="name" label="部门名称" align="center" width="120">
      </el-table-column>
      <el-table-column sortable prop="parentId" label="父级部门id" align="center" width="120">
      </el-table-column>
      <el-table-column sortable prop="parentName" label="父级部门名称" align="center" width="120">
      </el-table-column>
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="top-5"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="[5,10,15]"
      :page-size.sync="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total">
    </el-pagination>
    <!-- 编辑、添加界面 -->
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click="closeDialog">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="部门名称" prop="name">
          <el-input size="small" v-model="editForm.name" auto-complete="off" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="父级部门">
          <el-select v-model="editForm.parentId" placeholder="选择父级部门">
            <el-option v-for="item in parentNames" :key="item.deptId" :label="item.name" :value="item.deptId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog()">取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selectById, deptList, getBasicDepts, deptDelete, deptSave } from '../../api/userMG'
import Pagination from '../../components/Pagination'
export default {
  data() {
    return {
      // nshow: true, //switch开启
      // fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      title: '添加',

      parentNames:[],//表单
      editForm: {//编辑和添加的表单
        deptId:null,
        name:null,
        parentId:null,
        parentName:null,
        delFlag:0
      },
      // rules表单验证
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' }
        ],
        // deptNo: [{ required: true, message: '请输入部门代码', trigger: 'blur' }]
      },
      deleteid:"",// 删除部门id
      // userparm: [], //搜索权限
      listData: [], //用户数据
      // 分页参数
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 20,
        name:'',
      }
    }
  },
  // 注册组件
  components: {
    Pagination
  },
  /**
   * 数据发生改变
   */

  /**
   * 创建完毕
   */
  created() {
    this.getdata()
  },

  /**
   * 里面的方法只有被调用才会执行
   */
  methods: {
    handleSizeChange(){//点击 选择每页尺寸
      this.getdata()
    },
    handleCurrentChange(currentPage){//改变当前页时
      this.pagination.currentPage=currentPage
      this.getdata()
    },
    // 获取部门列表
    getdata() {
      this.loading = true

      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      deptList(this.pagination)
        .then(res => {
          this.loading = false
          // console.log(res)
          if (res.status !== 200) {
            this.$message({
              type: 'info',
              message: "获取数据出错"
            })
          } else {
            this.listData = res.data.list.records
            // 分页赋值
            this.pagination.currentPage = res.data.list.current
            this.pagination.pageSize = res.data.list.size
            this.pagination.total = res.data.list.total
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('获取部门信息加载失败，请稍后再试！')
        })
    },
    // 搜索事件
    search() {
      this.getdata()
    },

    getAllBasicDepts(){//获得所有的基础部门。即没有父级部门的部门
      getBasicDepts()
        .then(res => {
          this.parentNames = res.data.list
        }).catch(error=>{
          this.$message.error('获取基础部门失败，请稍后再试！')
          this.editFormVisible = false//关闭修改表单
        })
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true//显示修改表单
      if (row != undefined && row != 'undefined') {//如果传入的参数有定义则说明是编辑
        this.title = '修改'
        selectById(row.deptId)
          .then(res => {//根据部门id查询全部字段并显示在编辑页面上
            this.editForm = res.data.list//通过id查出来的数据保存到编辑表单中
            this.getAllBasicDepts()
          }).catch(error=>{
            this.$message.error('编辑失败，请稍后再试！')
            this.editFormVisible = false//关闭修改表单deptName
          })
      } else {
        this.title = '添加'
        this.getAllBasicDepts()
      }
    },
    // 编辑、增加页面保存方法
    submitForm(editData) {//提交这个编辑或添加的表单
      if(this.editForm.parentId===null){
        this.editForm.parentName=null
      }else{
        for(var i=0;i<this.parentNames.length;i++){
          if(this.editForm.parentId == this.parentNames[i].deptId){
            this.editForm.parentName = this.parentNames[i].name
          }
      }
      }
      this.$refs[editData].validate((valid) => {//验证表单
          if (valid) {
            deptSave(this.editForm)
            .then(res=>{
              this.getdata()
              this.$message({
                type: 'success',
                message: this.title+'成功'
              })
              this.editForm.delFlag = 0
              this.editForm.deptId = null
              this.editForm.name=null
              this.editForm.parentId=null
              this.editForm.parentName=null
              this.editFormVisible = false
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    // 删除部门
    deleteUser(index, row) {
      this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deptDelete(row.deptId)
            .then(res => {
              if (res.data.code === 0) {
                this.$message({
                  type: 'success',
                  message: '公司已删除!'
                })
                this.getdata()
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                })
              }
              this.getdata()
            })
            .catch(err => {
              this.loading = false
              this.$message.error('公司删除失败，请稍后再试！')
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.$message({
        type: 'info',
        message: '已取消'+this.title
      })
      this.editForm.delFlag = 0
      this.editForm.deptId = null
      this.editForm.name=null
      this.editForm.parentId=null
      this.editForm.parentName=null
      this.editFormVisible = false
    }
  }
}
</script>

<style scoped>
.top-5{
  margin-top: 10px;
}
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>


